# 部署脚本 - 将服务部署到服务器指定路径
param(
    [string]$ServerPath = "D:\Service\Lzfy_His_Service",
    [switch]$Build,
    [switch]$Deploy,
    [switch]$InstallService,
    [switch]$StartService,
    [switch]$StopService,
    [switch]$UpdateConfig
)

# 源路径（当前项目路径）
$sourcePath = $PSScriptRoot

Write-Host "=== HIS退费服务部署脚本 ===" -ForegroundColor Green
Write-Host "源路径: $sourcePath" -ForegroundColor Cyan
Write-Host "目标路径: $ServerPath" -ForegroundColor Cyan

function Build-Service {
    Write-Host "构建服务..." -ForegroundColor Yellow
    Set-Location $sourcePath
    dotnet publish --configuration Release --output "bin\Release\net9.0\publish" --no-self-contained
    if ($LASTEXITCODE -ne 0) {
        Write-Host "构建失败" -ForegroundColor Red
        exit 1
    }
    Write-Host "构建成功" -ForegroundColor Green
}

function Deploy-Service {
    Write-Host "部署服务到服务器..." -ForegroundColor Yellow
    
    # 创建目标目录
    if (-not (Test-Path $ServerPath)) {
        New-Item -ItemType Directory -Path $ServerPath -Force
    }
    
    # 复制文件
    $publishPath = Join-Path $sourcePath "bin\Release\net9.0\publish"
    if (Test-Path $publishPath) {
        Write-Host "复制发布文件..." -ForegroundColor Yellow
        Copy-Item -Path "$publishPath\*" -Destination $ServerPath -Recurse -Force
    } else {
        Write-Host "发布目录不存在，先执行构建..." -ForegroundColor Yellow
        Build-Service
        Copy-Item -Path "$publishPath\*" -Destination $ServerPath -Recurse -Force
    }
    
    # 复制配置文件
    Write-Host "复制配置文件..." -ForegroundColor Yellow
    Copy-Item -Path "$sourcePath\appsettings.json" -Destination $ServerPath -Force
    
    # 创建日志目录
    $logPath = Join-Path $ServerPath "logs"
    if (-not (Test-Path $logPath)) {
        New-Item -ItemType Directory -Path $logPath -Force
    }
    
    Write-Host "部署完成" -ForegroundColor Green
}

function Install-ServerService {
    Write-Host "在服务器上安装Windows服务..." -ForegroundColor Yellow
    
    # 检查管理员权限
    if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
        Write-Host "请以管理员身份运行此脚本" -ForegroundColor Red
        exit 1
    }
    
    $exePath = Join-Path $ServerPath "Lzfy_His_Service.exe"
    
    # 创建服务器专用的服务安装脚本
    $serviceScript = @"
# 服务器服务安装脚本
`$serviceName = "LzfyHisService"
`$serviceDisplayName = "HIS退费审核服务"
`$serviceDescription = "HIS退费审核管理系统后台服务"
`$exePath = "$exePath"

Write-Host "安装服务: `$serviceName" -ForegroundColor Green

# 停止并删除现有服务
Stop-Service -Name `$serviceName -Force -ErrorAction SilentlyContinue
Start-Sleep -Seconds 2
& sc.exe delete `$serviceName

# 创建新服务
& sc.exe create `$serviceName binPath= `"`$exePath`" DisplayName= `"`$serviceDisplayName`" start= auto obj= LocalSystem
& sc.exe description `$serviceName `$serviceDescription
& sc.exe failure `$serviceName reset= 86400 actions= restart/60000/restart/60000/restart/60000

Write-Host "服务安装完成" -ForegroundColor Green
Write-Host "启动服务: Start-Service -Name `$serviceName" -ForegroundColor Yellow
"@
    
    $installScriptPath = Join-Path $ServerPath "install-service-server.ps1"
    $serviceScript | Out-File -FilePath $installScriptPath -Encoding UTF8
    
    Write-Host "服务安装脚本已创建: $installScriptPath" -ForegroundColor Green
    Write-Host "请在服务器上运行此脚本安装服务" -ForegroundColor Yellow
}

function Update-ServerConfig {
    Write-Host "更新服务器配置文件..." -ForegroundColor Yellow
    
    $configPath = Join-Path $ServerPath "appsettings.json"
    if (Test-Path $configPath) {
        $config = Get-Content $configPath | ConvertFrom-Json
        
        # 更新日志路径
        $config.Serilog.WriteTo[1].Args.path = "logs/service-.log"
        
        # 保存配置
        $config | ConvertTo-Json -Depth 10 | Out-File -FilePath $configPath -Encoding UTF8
        Write-Host "配置文件已更新" -ForegroundColor Green
    }
}

# 执行操作
switch ($true) {
    $Build { Build-Service }
    $Deploy { Deploy-Service }
    $InstallService { Install-ServerService }
    $UpdateConfig { Update-ServerConfig }
    default {
        Write-Host "使用方法:" -ForegroundColor Cyan
        Write-Host "  .\deploy-to-server.ps1 -Build -Deploy -InstallService" -ForegroundColor Yellow
        Write-Host "  .\deploy-to-server.ps1 -Deploy" -ForegroundColor Yellow
        Write-Host "  .\deploy-to-server.ps1 -UpdateConfig" -ForegroundColor Yellow
    }
}